透過 session 的機制,可建立簡單的帳號身分確認的功能。
啟用 session 功能
Sinatra 預設並不啟動 Session 機制,
通常在瀏覽器端看到的回應標頭是這個樣子:
$ curl -I http://i5.tagbible.net/
HTTP/1.1 200 OK
Server: nginx/1.2.4
Date: Wed, 17 Oct 2012 09:04:55 GMT
Content-Type: text/html;charset=utf-8
Content-Length: 50
Connection: keep-alive
X-Frame-Options: sameorigin
X-XSS-Protection: 1; mode=block
在程式檔裡的前面加上這一行:
enable :sessions
瀏覽器的回應標頭變成:
$ curl -I http://i5.tagbible.net/
HTTP/1.1 200 OK
Server: nginx/1.2.4
Date: Wed, 17 Oct 2012 09:07:30 GMT
Content-Type: text/html;charset=utf-8
Content-Length: 50
Connection: keep-alive
X-Frame-Options: sameorigin
X-XSS-Protection: 1; mode=block
Set-Cookie: rack.session=BAh7B0kiD3Nlc3Npb25faWQGOgZFRiJFODE5MzE1ZmYzMmJkM2U4ZGQ4MjVm%0AMzYyMGYwZjNjMDViMGI0Y2M1N2EwYzQyYzRhMWU5NWQ5ZmViMmJmMGRhZEki%0ADXRyYWNraW5nBjsARnsISSIUSFRUUF9VU0VSX0FHRU5UBjsARiItNzU5Njg0%0AY2E3ODNhYTRkMTk5ZmE4NWU5OTQ1MTQ1YzYwZTY2NDI0ZUkiGUhUVFBfQUND%0ARVBUX0VOQ09ESU5HBjsARiItZGEzOWEzZWU1ZTZiNGIwZDMyNTViZmVmOTU2%0AMDE4OTBhZmQ4MDcwOUkiGUhUVFBfQUNDRVBUX0xBTkdVQUdFBjsARiItZGEz%0AOWEzZWU1ZTZiNGIwZDMyNTViZmVmOTU2MDE4OTBhZmQ4MDcwOQ%3D%3D%0A; path=/; HttpOnly
就透過背後的cookies來記住目前的session代碼。
簡單的session讀取、寫入、清除動作
測試一下簡單的session機制:
get '/mysession' do
session[:hi] ||= nil
"Session: #{session[:hi]}<br />#{session.inspect.to_s}<br /><a href=/logout>登出</a>"
end
get '/logout' do
session.clear
redirect '/mysession'
end
get '/setsession/:hi' do
session[:hi] = params[:hi]
redirect '/mysession'
end
了解基本的 session 操作,
就可以此為基礎建置帳號的機制。